package com.relytosoft.mizar.media.analyze.services.service.behavior.impl;


import com.alibaba.fastjson.JSON;
import com.relytosoft.dubhe.common.redis.utils.RedisUtil;
import com.relytosoft.mizar.media.analyze.services.service.behavior.AyBehaviorAlarmService;
import com.relytosoft.mizar.media.analyze.services.service.behavior.AyBehaviorControlService;
import com.relytosoft.mizar.media.analyze.services.service.control.ControlVerifyService;
import com.relytosoft.mizar.media.common.entity.pojo.dto.AyDispositionPlanDto;
import com.relytosoft.mizar.media.common.entity.pojo.request.btdl.common.BtdlBehaviorDataReq;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;
import java.util.Objects;

import static com.relytosoft.mizar.media.common.constant.AyCacheConstants.RAW_BEHAVIOR_CONDITION;

/**
 * @author wss
 * @version 1.0
 * @date 2022/5/23 17:08
 */
@Service
public class AyBehaviorControlServiceImpl implements AyBehaviorControlService {

    protected Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    AyBehaviorAlarmService ayBehaviorAlarmService;
    @Autowired
    ControlVerifyService controlVerifyService;

    @Override
    public Boolean rawBehaviorVerify(BtdlBehaviorDataReq btdlBehaviorDataReq) {
        String deviceID = btdlBehaviorDataReq.getDeviceID();
        Object controlDto = RedisUtil.get(RAW_BEHAVIOR_CONDITION + deviceID);
        //判定布控条件是否存在
        if (Objects.isNull(controlDto)) {
            return false;
        }
        List<AyDispositionPlanDto> ayDispositionPlanDtoS = JSON.parseArray(controlDto.toString(), AyDispositionPlanDto.class);
        Iterator<AyDispositionPlanDto> planDtoIterator = ayDispositionPlanDtoS.iterator();
        while (planDtoIterator.hasNext()) {
            AyDispositionPlanDto dispositionPlanDto = planDtoIterator.next();
            if (singleRawBehaviorVerify(dispositionPlanDto, btdlBehaviorDataReq)) {
                ayBehaviorAlarmService.behaviorAlarm(dispositionPlanDto, btdlBehaviorDataReq);
                return true;
            }
        }
        return false;
    }

    /**
     * 单个行为分析数据布控验证
     *
     * @param ayDispositionPlanDto
     * @param btdlBehaviorDataReq
     * @return
     */
    public Boolean singleRawBehaviorVerify(AyDispositionPlanDto ayDispositionPlanDto, BtdlBehaviorDataReq btdlBehaviorDataReq) {
        Long markTime = btdlBehaviorDataReq.getMarkTime();
        //前置验证
        if (!controlVerifyService.controlFrontVerify(ayDispositionPlanDto, markTime)) {
            return false;
        }
        //布控计划验证
        return controlVerifyService.controlTemplateVerify(ayDispositionPlanDto);
    }
}
